﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace _9._26bao
{
    internal class IniFile
    {
        private string filePath;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        public IniFile(string filePath)
        {
            this.filePath = filePath;
            if (!File.Exists(filePath))
            {
                File.Create(filePath).Close();
            }
        }

        public void WriteValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, filePath);
        }

        public string ReadValue(string section, string key, string defaultValue = "")
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, "", temp, 255, filePath);
            return temp.Length > 0 ? temp.ToString() : defaultValue;
        }

        // 专门为本地相机优化的参数保存方法
        public void WriteLocalCameraParameters(string cameraName, string interfaceType, int deviceIndex,
            int exposureTime = 10000, double gain = 1.0, string pixelFormat = "default")
        {
            WriteValue("LocalCamera", "CameraName", cameraName);
            WriteValue("LocalCamera", "InterfaceType", interfaceType);
            WriteValue("LocalCamera", "DeviceIndex", deviceIndex.ToString());
            WriteValue("LocalCamera", "ExposureTime", exposureTime.ToString());
            WriteValue("LocalCamera", "Gain", gain.ToString());
            WriteValue("LocalCamera", "PixelFormat", pixelFormat);
            WriteValue("LocalCamera", "LastConnected", DateTime.Now.ToString());
        }

        public (string cameraName, string interfaceType, int deviceIndex, int exposureTime, double gain, string pixelFormat) ReadLocalCameraParameters()
        {
            return (
                ReadValue("LocalCamera", "CameraName", "本地USB相机"),
                ReadValue("LocalCamera", "InterfaceType", "USB3Vision"), // 默认使用USB3Vision
                int.Parse(ReadValue("LocalCamera", "DeviceIndex", "0")),
                int.Parse(ReadValue("LocalCamera", "ExposureTime", "10000")),
                double.Parse(ReadValue("LocalCamera", "Gain", "1.0")),
                ReadValue("LocalCamera", "PixelFormat", "default")
            );
        }
    }
}
